from apps import jsonrpc_v1
from .models import db,GoodsSPU,GoodsCategory

@jsonrpc_v1.method('Goods.home_goods')
def home_goods():
    '''首页今日心品'''
    good_list = GoodsSPU.query.filter(
        GoodsSPU.is_show ==True,
        GoodsSPU.is_deleted ==False,
        GoodsSPU.is_recommend == True
    ).order_by(
        GoodsSPU.sort.asc(),
        GoodsSPU.id.desc()
    ).limit(5).all()

    data =[]

    for goods in good_list:
        '''把列表中每个对象转换成字典'''
        data.append(goods.__to_dict__(['id','title','image_url']))

    return data

@jsonrpc_v1.method('Goods.goods_category')
def goods_categoty():
    '''商品分类'''
    cat_list = GoodsCategory.query.filter(
        GoodsCategory.is_show ==True,
        GoodsCategory.is_deleted ==False
    ).order_by(
        GoodsCategory.sort.asc(),
        GoodsCategory.id.desc()
    ).limit(6).all()

    data = []
    for category in cat_list:
        '''把列表中每个对象转换成字典'''
        data.append(category.__to_dict__(['id','name']))
    return data


@jsonrpc_v1.method("Goods.list_goods(category=int,page=int,size=int)")
def list_goods(category=None, page=1, size=10):
	"""商品列表"""
	query = GoodsSPU.query.filter(
		GoodsSPU.is_show==True,
		GoodsSPU.is_deleted==False
	)

	if category is not None:
		query = query.filter(GoodsSPU.category_id==category)#通过商品关联的商品分类来获取 所有分类商品中的商品

	paginate = query.order_by(
		GoodsSPU.sort.asc(),
		GoodsSPU.id.desc()
	).paginate(page,size)

	# 分页器也要转换成字典
	data = {}
	data["page"] = paginate.page
	data["pages"] = paginate.pages
	data["has_prev"] = paginate.has_prev
	data["has_next"] = paginate.has_next
	data["next_num"] = paginate.next_num
	data["prev_num"] = paginate.prev_num
	# 设置分页器里面的每一页数据项
	data["items"] = []
	for goods in paginate.items:
		"""把列表中每个对象转换成字典"""
		data["items"].append( goods.__to_dict__(["id","title","image_url"]) )

	return data